﻿using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Znice.Test
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
            dgv.AutoGenerateColumns = false;
        }

        private IList<RichDemo> LoadData()
        {
            IList<RichDemo> list = new List<RichDemo>();          
            // 定义 SQLite 连接字符串
            string connectionString = "Data Source=demo.db;";

            // 创建一个新的 SQLite 连接
            using (SqliteConnection connection = new SqliteConnection(connectionString))
            {
                // 打开连接
                connection.Open();

                // 定义 SQL 查询语句
                string sql = "SELECT * FROM RichDemo ORDER BY Id DESC LIMIT 100";

                // 创建一个新的 SQLite 命令对象
                using (SqliteCommand command = new SqliteCommand(sql, connection))
                {
                    // 执行查询
                    using (SqliteDataReader reader = command.ExecuteReader())
                    {
                       
                        // 循环读取结果集中的行
                        while (reader.Read())
                        {
                            // 获取每一行的列数据
                            list.Add(new()
                            {
                                Id = reader.GetInt32(0),
                                Title = reader.GetString(1),
                                Content = (byte[])reader.GetValue(2)
                            });
                        }
                    }
                }
            }

            return list;
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            dgv.DataSource = LoadData();
        }

        private void OpenEditor(RichDemo? model = null)
        {
            FrmEditor f = new(model);
            if (f.ShowDialog() == DialogResult.OK)
            {
                dgv.DataSource = LoadData();
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            OpenEditor();
        }

        private void dgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                OpenEditor(dgv.CurrentRow.DataBoundItem as RichDemo);
            }
        }
    }
}
